<?php

namespace app\controller\api;

use ali\Sms;
use app\BaseController;
use app\model\CouponOrder;
use app\model\User;
use app\model\UserBalance;
use app\model\UserCar;
use app\model\UserChangeScore;
use app\model\UserValidateBalance;
use think\facade\Cache;
use think\helper\Str;
use think\response\Json;

class Membership extends BaseController
{
    public function login(): Json
    {
        if (!$this->request->isPost()) throw new \Exception('请求方式错误', 7065);
        $account = $this->app->make(User::class)->findOrRegister();
        $code = Cache::get("user_login_code_$account[mobile]");
        if (empty($code)) throw new \Exception("验证码已失效", 7001);
        if (strtolower($code) != strtolower($this->request->post('verifyCode'))) throw new \Exception("验证码错误", 7003);
        Cache::delete("user_login_code_$account[mobile]");
        return $this->success(['id' => $account['id'], 'last_time' => strtotime("+7 day")]);
    }

    public function code(): Json
    {
        if (!$this->request->isPost()) throw new \Exception('请求方式错误', 7065);
        $mobile = $this->request->post('mobile');
        $this->app->make(User::class)->findOrRegister();
        //校验今日获取登录验证码次数
        $todayTimes = Cache::get("user_login_code_timer_$mobile", 1);
        if ($todayTimes > 5) throw new \Exception("今日获取登录验证码次数过多", 7005);
        $lockTimer = Cache::get("user_login_code_lock_$mobile");
        if ($lockTimer) throw new \Exception("获取登录验证码过于频繁", 7006);
        //缓存验证码
        $lastTime = strtotime(date("Y-m-d 23:59:59"));
        $ttl = $lastTime - time();
        if ($this->request->ip() != "127.0.0.1") {
            $code = Str::random(6, 1);//验证码
            $send = sendSms("191585", $mobile, compact("code"));
            if (empty($send)) throw new \Exception("短信发送失败", 7002);
        } else {
            $code = 123456;
        }

        Cache::set("user_login_code_timer_$mobile", $todayTimes + 1, $ttl);
        Cache::set("user_login_code_lock_$mobile", 1, 60);
        Cache::set("user_login_code_$mobile", $code, 300);
        return $this->success();
    }

    public function query(): Json
    {
        if (empty($this->request->param("id"))) throw new \Exception('请登录', 7065);
        return $this->success($this->app->make(User::class)->detail());
    }

    public function balanceTotal(): Json
    {
        if (empty($this->request->param("uid"))) throw new \Exception('请登录', 7065);
        return $this->success($this->app->make(UserBalance::class)->balanceTotal());
    }

    public function changeNotice(): Json
    {
        if (empty($this->request->param("uid"))) throw new \Exception('请登录', 7065);
        return $this->success(["total" => $this->app->make(UserBalance::class)->balanceCht()]);
    }

    public function transfer(): Json
    {
        if (!$this->request->isPost()) throw new \Exception('请求方式错误', 7065);
        $data = $this->request->post();
        if (empty($data['uid'])) throw new \Exception('请登录', 7065);
        //获取用户
        $user = $this->app->make(User::class);
        $balance = $user->where('id', '=', $data['uid'])->where('balance', '>=', $data['transferScore'] * 100)->count();
        if ($balance < 1) throw new \Exception('积分不足', 7065);
        $reg = $user->findOrRegister();
        $user->startTrans();
        $order = [
            "change_code" => date("ymdHis") . Str::random(8, 1),
            "number" => bcmul($data['transferScore'], 100),
            "uid" => $data['uid'],
            "change_uid" => $reg['id']
        ];
        $this->app->make(UserChangeScore::class)->save($order);
        $balance_data = [
            [
                "uid" => $data['uid'],
                "content" => "转让给：$reg[mobile]",
                "number" => $order['number'],
                "type" => 4
            ],
            [
                "uid" => $reg['id'],
                "content" => "他人转让积分",
                "number" => $order['number'],
                "type" => 1
            ]
        ];
        $this->app->make(UserBalance::class)->saveAll($balance_data);
        //更改用户积分
        $user->where(['id' => $reg['id']])->inc("balance", $order['number'])->save();
        $user->where(['id' => $data['uid']])->dec("balance", $order['number'])->save();
        (new UserValidateBalance)->addBalance($reg['id'], $order['number']);
        //获取转让人积分有效期数据
        (new UserValidateBalance)->decUpdateBalance($data['uid'],$order['number']);
        $user->commit();
        return $this->success();
    }

    public function changeScore(): Json
    {
        if (empty($this->request->param("uid"))) throw new \Exception('请登录', 7065);
        return $this->success($this->app->make(UserChangeScore::class)->getPage());
    }

    public function userCar(): Json
    {
        if (empty($this->request->param("uid"))) throw new \Exception('请登录', 7065);
        return $this->success($this->app->make(UserCar::class)->getPage());
    }

    public function deleteCar(): Json
    {
        if (!$this->request->isDelete()) throw new \Exception('请求方式错误', 7065);
        if (empty($this->request->param("uid"))) throw new \Exception('请登录', 7065);
        return $this->success($this->app->make(UserCar::class)->deleteCar());
    }

    public function addCar(): Json
    {
        if (!$this->request->isPost()) throw new \Exception('请求方式错误', 7065);
        if (empty($this->request->param("uid"))) throw new \Exception('请登录', 7065);
        return $this->success($this->app->make(UserCar::class)->addCar());
    }

    public function userBill(): Json
    {
        if (empty($this->request->param("uid"))) throw new \Exception('请登录', 7065);
        $create = [date("Y-m-d 00:00:00", strtotime("-30 day")), date("Y-m-d")];
        $bill = $this->app->make(UserBalance::class)->where('create_time', 'between', $create)->where(['uid' => $this->request->param("uid")])->field("sum(number) money,type,create_time")->order('create_time desc')->group('type,create_time')->select()->toArray();
        if (empty($bill)) throw new \Exception('没有数据', 7065);
        $its = [];
        foreach ($bill as $value) {
            $money = $value['money'] > 0 ? bcdiv($value['money'], 100, 2) : 0;
            $ctime = date("Y年n月j日", strtotime($value['create_time']));
            $its[$ctime] = $its[$ctime] ?? [];
            $its[$ctime][$value['type']] = bcadd($its[$ctime][$value['type']] ?? 0, $money, 2);
            $its[$ctime]['total'] = match ($value['type']) {
                1 => bcadd($its[$ctime]['total'] ?? 0, $money, 2),
                default => bcsub($its[$ctime]['total'] ?? 0, $money, 2),
            };
        }
        return $this->success(['data' => $its, 'active' => date("Y年n月j日", strtotime($bill[0]['create_time']))]);
    }

    public function userDiscountData(): Json
    {
        if (empty($this->request->param("uid"))) throw new \Exception('请登录', 7065);
        $coupon = $this->app->make(CouponOrder::class)->with(['couponOrder'])->where(['uid' => $this->request->param('uid'), 'state' => 1])->limit(3)->select()->toArray();
        if (!empty($coupon)) {
            $items = [];
            foreach ($coupon as $key => $value) {
                $cou = $value['couponOrder'];
                if (!empty($cou)) {
                    foreach ($cou as $v) {
                        if ($v['term'] > time() && $v['state'] == 0) {
//                            $term
                            if (isset($items[$v['cid']])) {
                                $items[$v['cid']]['count']++;
                            } else {
                                $v['term'] = date("Y年n月j日", $v['term']);
                                $items[$v['cid']] = array_merge($v, ['count' => 1]);
                            }
                        }
                    }
                }
            }
        }
        $items = empty($items) ? [] : array_values($items)[0];
        return $this->success(['data' => $items]);
    }
}
